package org.qengine.utils;

import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.qengine.entity.QuestionEntity;
import org.springframework.web.multipart.MultipartFile;

import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;

public class DocxParser {
    public static List<QuestionEntity> parseDocx(InputStream inputStream, Integer courseId) throws Exception{
        List<QuestionEntity> questions = new ArrayList<>();
        try (XWPFDocument document = new XWPFDocument(inputStream)) {
            for (XWPFParagraph paragraph : document.getParagraphs()) {
                String text = paragraph.getText();
                if (!text.isEmpty()) {
                    QuestionEntity question = parseQuestion(text, courseId);
                    if (question != null) {
                        questions.add(question);
                    }
                }
            }
        }
        return questions;
    }

    private static QuestionEntity parseQuestion(String text, Integer courseId) {
        //通过知识点表获取信息，填充课程id和知识点id
        //通过题干的形式获取题型id
        //通过答案的形式获取是否是多选题
        //questionStem|Answer
        String[] parts = text.split("\\|");
        QuestionEntity question = new QuestionEntity();
        //获取题型
        if(parts[0].contains("@")){
            if(parts[1].contains("@")){
                question.setTypeID(2);//多选
            }
            else{
                question.setTypeID(1);//单选
            }
        }
        else if(parts[0].contains("____")){
            question.setTypeID(3);//填空
        }
        else if(parts[1].contains("Y") || parts[1].contains("N")){
            question.setTypeID(4);//判断
        }

        question.setQuestionStem(parts[0]);
        question.setQuestionAnswer(parts[1]);
        question.setCourseID(courseId);
        question.setKnowledgeID(new Random().nextInt(5));
        question.setDLevel(new Random().nextInt(4));
        question.setAnswerCount(0);
        question.setWrongCount(0);

        return question;
    }
}
